<?php

$client_obj = new client_obj();
$record_obj = new record_obj();
$user_obj = new user_obj();
$tariff_obj = new tariff_obj();
$lock_obj = new lock_obj();
$periods = array();

if (!empty($_REQUEST['action']) && ($_REQUEST['action'] == 'lock')) {
    $in_data = array();
    $selectedPeriodExplode = explode('/', $_REQUEST['selectedPeriod']);
    $in_data['month'] = $selectedPeriodExplode[0];
    $in_data['year'] = $selectedPeriodExplode[1];
    $in_data['type'] = 'record';

    $is_locked = $lock_obj->getLocks($in_data);
    if (!error_obj::isError($is_locked) && !empty($is_locked)) {
        $result = $lock_obj->deleteLockRow($in_data['month'], $in_data['year'], $in_data['type']);
        if (error_obj::isError($result))
            error_obj::setError($result, UNEXCEPTED);
        else
            error_obj::setGood('Selected period was unlocked!');
    } else {
        $result = $lock_obj->addLock($in_data);
        if (error_obj::isError($result))
            error_obj::setError($result, UNEXCEPTED);
        else
            error_obj::setGood('Selected period was locked!');
    }
}
for ($i = 2013; $i < date("Y") + 2; $i++) {
    for ($j = 1; $j < 13; $j++) {

        $temp = array(
            'period' => str_pad($j, 2, "0", STR_PAD_LEFT) . '/' . $i
        );

        $filter = array(
            'month' => $j,
            'year' => $i,
            'type' => 'record'
        );
        $lock = $lock_obj->getLocks($filter);

        if (!error_obj::isError($lock) && !empty($lock))
            $temp['locked'] = 1;
        else
            $temp['locked'] = 0;

        $periods[] = $temp;
    }
}

$filter = array(
    'active' => 0
);
if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
    $filter['clients'] = $_SESSION['user']['clients'];
}
$clients = $client_obj->getAllClients('klient_id, name, bad_payer', $filter, 'name ASC');
$GLOBALS['template_data']['clients'] = $clients;

$GLOBALS['template_data']['periods'] = $periods;
$GLOBALS['template_data']['prefill']['today'] = date("m/Y");

$do = false;
$filter = array();

if (!empty($_REQUEST['action']) && ($_REQUEST['action'] == 'show')) {
    if (!empty($_REQUEST['selectedFrom']) && !empty($_REQUEST['selectedTo'])) {
        $GLOBALS['template_data']['prefill']['from'] = $_REQUEST['selectedFrom'];
        $GLOBALS['template_data']['prefill']['to'] = $_REQUEST['selectedTo'];
        $filter['date-equal-higher'] = base_obj::convertDateTo($_REQUEST['selectedFrom']);
        $filter['date-equal-lower'] = base_obj::convertDateTo($_REQUEST['selectedTo']);
        if ($_REQUEST['goods'] == 1 || $_REQUEST['servis'] == 1 || $_REQUEST['other'] == 1)
            $do = true;
    } elseif (!empty($_REQUEST['selectedPeriod'])) {
        $GLOBALS['template_data']['prefill']['today'] = $_REQUEST['selectedPeriod'];
        $selectedPeriodExplode = explode('/', $_REQUEST['selectedPeriod']);
        $GLOBALS['template_data']['prefill']['todayMonth'] = base_obj::getMonthName((int) $selectedPeriodExplode[0]);
        $GLOBALS['template_data']['prefill']['todayYear'] = $selectedPeriodExplode[1];
        $filter['monthm'] = $selectedPeriodExplode[0];
        $filter['year'] = $selectedPeriodExplode[1];
        if ($_REQUEST['goods'] == 1 || $_REQUEST['servis'] == 1 || $_REQUEST['other'] == 1)
            $do = true;
    }
}

if ($do) {
    if (!empty($_REQUEST['selectedClient'])) {
        $filter['client'] = $_REQUEST['selectedClient'];
        $GLOBALS['template_data']['prefill']['client'] = $_REQUEST['selectedClient'];
        
        $task_obj = new task_obj();
        $f = array(
            'client' => $filter['client']
        );
        $order = array(
            'col' => 'created',
            'orderBy' => 'created',
            'order' => 'DESC',
            'table' => '',
            'connector' => ''
        );
        $tasks = $task_obj->getListOfTasks($f, $order);
        $GLOBALS['template_data']['tasks'] = $tasks;
    }
    if (!empty($_REQUEST['selectedTask'])) {
        $filter['taskId'] = $_REQUEST['selectedTask'];
        $GLOBALS['template_data']['prefill']['task'] = $_REQUEST['selectedTask'];
    }
    $ors = array();
    if ($_REQUEST['goods'] == 1) {
        $temp = array();
        $temp['type'] = 8;  // dodanie tovaru
        $ors[] = $temp;
    }
    if ($_REQUEST['servis'] == 1) {
        $temp = array();
        $temp['tariff'] = 6;  // pravidelny servis
        $ors[] = $temp;
    }
    if ($_REQUEST['other'] == 1) {
        $temp = array();
        $temp['nottype'] = 8; // nie dodanie tovaru
        $temp['nottariff'] = 6; // nie pravidelny servis
        $ors[] = $temp;
    }

    if ($_REQUEST['goods'] == 1) {
        if ($_REQUEST['other'] == 1) {
            $possible_types = array(1, 3, 4, 8);
        } elseif ($_REQUEST['servis'] == 1) {
            $possible_types = array(1, 8);
        } else {
            $possible_types = array(8);
        }
    } elseif ($_REQUEST['servis'] == 1) {
        if ($_REQUEST['other'] == 1) {
            $possible_types = array(1, 3, 4);
        } else {
            $possible_types = array(1);
        }
    } elseif ($_REQUEST['other'] == 1) {
        $possible_types = array(1, 3, 4);
    }

    $filter['ors'] = $ors;

    base_obj::debug('possible', $possible_types);

    $clients = $record_obj->getListOfRecords($filter, '', '', 'client', 'client');

    $output_records = array();
    $output_sums = array();
    $total_sums = array();
    $total_sums['withoutDph'] = 0;
    $total_sums['withDph'] = 0;

    if (error_obj::isError($clients)) {
        error_obj::setError($clients, UNEXCEPTED);
        return false;
    }

    if (!empty($clients)) {

        $records_type = $record_obj->getRecordTypes('Id ASC');

        foreach ($clients as $client_key => $client) {
            $output_records[$client['client']] = array();
            $output_records[$client['client']]['client_info'] = $client_obj->getClient($client['client']);
            if (!empty($output_records[$client['client']]['client_info']['contactPerson'])) {
                $output_records[$client['client']]['contact_info'] = $user_obj->getUserById($output_records[$client['client']]['client_info']['contactPerson']);
            }
            $output_records[$client['client']]['total']['withoutDph'] = 0;
            $output_records[$client['client']]['total']['withDph'] = 0;
            $output_records[$client['client']]['types'] = array();
            $output_records[$client['client']]['sums'] = array();
            foreach ($records_type as $type_key => $type) {

                if (in_array($type['Id'], $possible_types)) {
                    
                    $filter['type'] = $type['Id'];
                    $filter['client'] = $client['client'];
                    $sk = array(
                        1 => 'Vykonané práce',
                        3 => 'Doprava',
                        4 => 'Príjazd do hodiny',
                        8 => 'Dodaný tovar',
                    );
                    $type['type_of_record'] = $sk[$type['Id']];
                    $records = $record_obj->getListOfRecords($filter);
                    if (!error_obj::isError($records) && !empty($records)) {
                        $output_records[$client['client']]['sums'][$type['type_of_record']]['withoutDph'] = 0;
                        $output_records[$client['client']]['sums'][$type['type_of_record']]['withDph'] = 0;
                        $output_records[$client['client']]['sums'][$type['type_of_record']]['totalAmount'] = 0;
                        foreach ($records as $key => $record) {
                            $records[$key]['date_formated'] = base_obj::convertDateTo($record['date'], 'dd/mm/yyyy', 'date');
                            $records[$key]['user_info'] = $user_obj->getUserById($record['user_id']);
                            $records[$key]['withoutDph'] = ($record['amount'] * $record['unit_price']);
                            $records[$key]['withDph'] = ($record['amount'] * $record['unit_price']) * (1 + DPH);
                            if ($type['Id'] == 1)
                                $records[$key]['tariff_info'] = $tariff_obj->getTariffById($record['tariff']);
                            else
                                $records[$key]['tariff_info']['title'] = '';
                            $output_records[$client['client']]['sums'][$type['type_of_record']]['withoutDph'] += $records[$key]['withoutDph'];
                            $output_records[$client['client']]['sums'][$type['type_of_record']]['withDph'] += $records[$key]['withDph'];
                            $output_records[$client['client']]['sums'][$type['type_of_record']]['totalAmount'] += $records[$key]['amount'];
                        }
                        $output_records[$client['client']]['types'][$type['type_of_record']] = $records;
                        $output_records[$client['client']]['total']['withoutDph'] += $output_records[$client['client']]['sums'][$type['type_of_record']]['withoutDph'];
                        $output_records[$client['client']]['total']['withDph'] += $output_records[$client['client']]['sums'][$type['type_of_record']]['withDph'];
                    }
                }
            }
        }
    }

    $GLOBALS['template_data']['output'] = $output_records;
}
?>
